package java202507;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class 两数之和 {

    public static void main(String[] args) {
            int[] nums = new int[]{3,2,4};
        System.out.println(nums.length);
        for (int i : twoSum(nums, 6)) {
            System.out.println(i);
        }

    }


    /**
     * 暴力循环
     */
    public static int[] twoSum(int[] nums, int target) {
        for (int i = 0; i <= nums.length-2; i++) {
            for (int j = i+1; j <= nums.length-1; j++) {
                int total = nums[i] + nums[j];
                if (total == target) {
                    return new int[]{i, j};
                }
            }
        }
        return new int[0];
    }

    /**
     * 写map存储遍历过的数据
     */
    public static int[] twoSum1(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i <= nums.length-1; i++) {
            int except = target - nums[i];//期待相匹配的值
            if (map.containsKey(except)) {//寻找现有存储的key
                return new int[]{map.get(except),i};
            }
            map.put(nums[i], i);//把遍历过的值和值坐标存起来
        }
        return new int[0];
    }
}
